/**
 * Created by Feng Yapeng on 2015/8/30.
 */
// 详细页面依赖的js
//联系人操作方法
var contactorOperateEvents = {
    'click .edit': function (e, value, row, index) {
        $("#contactorForm").validate().resetForm();
        var modal = $('#contactorModal');
        $("#modalLabel").text("修改联系人");
        for (var name in row) {
            $("#contactorForm").find(".control-group [name=" + name + "]").val(row[name]);
        }
        $("#contactorId").val(row.id);
        $('#contactorModal').modal("show");
    },
    'click .remove': function (e, value, row, index) {
        confirmx("确认要删除该联系人吗？", function () {
            $.post(ctx + "/customer/potentialContactor/delete",
               {id: row.id},
               function (data) {
                   $("#contactorTable").bootstrapTable('refresh');
               }
            );
        });
    }
};

function callFormatter(value, row, index){
    return [
        '<a class="call" href="javascript:void(0);">',
        value,
        '</a>'
    ].join('');
}

function contactorOperate(value, row, index) {
    return [
        '<a class="edit" href="javascript:void(0)" title="修改">',
        '<i class="icon icon-edit"></i>',
        '</a>  ',
        '<a class="remove" href="javascript:void(0)" title="删除">',
        '<i class="icon icon-remove"></i>',
        '</a>'
    ].join('');
}

// 合并事件
var mergeOperateEvents = {
    'click .resolve': function (e, value, row, index) {
        confirmx("确认要分解这条记录吗？", function () {
            $.post(ctx + "/customer/potentialCustomer/resolveData",
               {id: row.id,flag: $("#dataArea").data("flag")},
               function (data) {
                   $("#mergerTable").bootstrapTable('refresh');
               }
            );
        });
    }
};

function mergerOperate(value, row, index) {
    return [
        '<a class="resolve" href="javascript:void(0);" title="分解">',
        '分解',
        '</a>  ',
        '<a class="addTab" href="',
        ctx,
        '/customer/potentialCustomer/detail?id=',
        row.id,
        '" title="详情">',
        '详情',
        '</a>  '
    ].join('');
}

// 成单信息
var saleOperateEvents = {
    'click .edit': function (e, value, row, index) {
        $("#saleForm").validate().resetForm();
       var formElts =  $("#saleForm").find("input , textarea , select").not("[type='hidden']");
        $.each(formElts,function(i,elt){
            if($(elt).is("input") || $(elt).is("textarea")){
                $(elt).val(row[$(elt).attr("name")]);
            }
            if($(elt).is("select")){
                $(elt).find("option[value="+row[$(elt).attr("name")]+"]").attr("selected","selected");
            }
        });
        $("#saleId").val(row.id);
        $('#saleModal').modal("show");
    }
};

function saleOperate(value, row, index){
    return [
        '<a class="edit" href="javascript:void(0)" title="修改">',
        '<i class="icon icon-edit"></i>',
        '</a>  '
    ].join('');
}

// 我的预约
function appointment(value, row, index){
    if(row.appointmentDate) {
        return new Date(row.appointmentDate).pattern("yyyy-MM-dd HH:mm:ss") + (row.descn?("," + row.descn):"");
    }
    return "-";
}

//呼叫状态
function serviceDirectFormat(value, row, index){
    if(row.serviceDirect=="3"||row.serviceDirect=="1"){
        return "呼出";
    }else{
        return "呼入";
    }
}
//挂机方向
function disconnectTypeFormat(value, row, index){
    if(row.disconnectType=="2"){
        return "坐席挂机";
    }else{
        return "客户挂机";
    }
}
//销售记录
function visitRecordOperationType(value){
    return value.replace("CREATE","创建")
        .replace("DONE","成单")
        .replace("END","结束");
}
//呼叫操作
function callOperation(value, row, index){
    var array = [];
    array.push('<a class="download" href="javascript:void(0);" title="下载">');
    array.push('<i class="icon icon-download-alt"></i>');
    array.push('</a>');
    array.push('  ');
    array.push('<a class="play" href="javascript:void(0);" title="播放">');
    array.push('<i class="icon icon-headphones"></i>');
    array.push('</a>');
    return array.join('');
}

var operateEvents = {
    'click .download': function (e, value, row, index) {
        var url = $("#dataArea").data("base-path")+row.filePath;
        window.open(ctx+"/call/record/recordinfo/download?filePath="+url);
    },
    'click .play': function (e, value, row, index) {
        var url = $("#dataArea").data("base-path")+row.filePath;
        palyer(url);
    }
};

$(function () {
    $(".call").live("click",function(){// 注入打电话事件
        makeCall($(this).text(),{customerId:$("#dataArea").data("potentialcustomerid")});
    });
	//查看合并数据的详细信息，打开新的页签
	$(".addTab").live("click", function () {
        return window.parent.addTab($(this));
    });
    //初始化联系人列表
    $("#contactorTable").bootstrapTable($.fn.BTConfigSimple({
        pagination: false,
        queryParams: {
            potentialCustomerId: $("#dataArea").data("potentialcustomerid")
        }
    }));
    //初始化联系人模态框
    $('#contactorModal').modal({
    	backdrop: 'static',
    	keyboard: false,
    	show: false
    });
    //新增联系人事件
    $("#addContactorBtn").live("click", function () {
        var model = $('#contactorModal');
        $("#contactorForm").validate().resetForm();
        $(model).find("modalLabel").text("新增联系人");
        $("#contactorForm").find("input , textarea").not(".btn , #potentialCustomer").val("");//置空ID
        $('#contactorModal').modal("show");
    });
    //添加联系人操作
    $("#addContactSubmitBtn").live("click", function () {
    	var contactorForm = $("#contactorForm");
    	contactorForm.validate();
        if (contactorForm.valid()) {
            $.post(ctx + "/customer/potentialContactor/save", contactorForm.serialize(),
                   function (data) {
                       if (data.state) {
                    	   alertx(data.message,function(){
                               $("#contactorTable").bootstrapTable('refresh');
                               $("#contactorForm")[0].reset();
                               $('#contactorModal').modal("hide");
                           });
                       } else {
                    	   alertx(data.message,null,null,null,"error");
                       }
                   }
            );
        }
    });

    //初始化合并数据列表
    $("#mergerTable").bootstrapTable($.fn.BTConfigSimple({
        pagination: false,
        queryParams: {
            "parent.id": $("#dataArea").data("potentialcustomerid")
        }
    }));
    
    //初始化成单信息列表
    $("#saleTable").bootstrapTable($.fn.BTConfigSimple({
        pagination: false,
        queryParams: {
            potentialCustomerId: $("#dataArea").data("potentialcustomerid"),
            sortName: "a.lastUpdated",
            sortOrder: "desc"
        }
    }));
    
    //修改成单信息
    $("#addSaleSubmitBtn").click(function () {
    	var saleForm = $("#saleForm");
        saleForm.validate();
        if (saleForm.valid()) {
            $.post(ctx + "/customer/potentialAfterSalesService/save", saleForm.serialize(),
                   function (data) {
                       if (data.state) {
                    	   alertx(data.message,function(){
                    		   $("#saleForm")[0].reset();
                               $("#saleTable").bootstrapTable('refresh');
                               $('#saleModal').modal("hide");
                           });
                       } else {
                    	   alertx(data.message,null,null,null,"error");
                       }
                   }
            );
        }
    });

    //查询参数
	var params = {};
	//潜在客户ID
	params.potentialCustomerId = $("#dataArea").data("potentialcustomerid");
	//用户ID
    var _userId = $("#dataArea").data("user-id");

    //初始化销售跟踪信息列表
    $("#visitRecordTable").bootstrapTable($.fn.BTConfigSimple({
        pagination: false,
        queryParams: _userId? $.extend({createUserId:_userId},params):params
    }));

    //初始化回访记录列表
    $("#soundTable").bootstrapTable($.fn.BTConfigSimple({
        pagination: false,
        sortName: "a.lastUpdated",
        sortOrder: "desc",
        queryParams: _userId? $.extend({fromUserId:_userId},params):params
    }));
    
    //初始化分配信息列表
    $("#distTable").bootstrapTable($.fn.BTConfigSimple({
    	pagination: false,
    	queryParams: _userId? $.extend({executorId:_userId},params):params
    }));
});


